#-------TCP-----CLIENT----------
#!/usr/bin/python
#encoding=utf-8

#
# echo程序客户端，服务端把每条消息打上时间戳后返回
#

from socket import *
import sys

BUFSIZE = 1024
serverAddr = ('localhost', 2012)
clientSock = socket(AF_INET, SOCK_STREAM)

try:
    clientSock.connect(serverAddr) #若要连接的服务端没有启动，这里会抛出异常
except Exception as e: #不知道这里捕获什么具体的异常了，就用的一个比较基层的类Exception
    print 'exception catched : ' ,e
    sys.exit()

while True:
    data = raw_input('input data :')
    if not data:  # 直接回车就没有输入内容,退出
        print 'client quit'
        break    
    clientSock.send(data)
    data = clientSock.recv(BUFSIZE)
    print 'recieve : ', data

clientSock.close() # 要close一下

#------TCP-SERVER-------------


#!/usr/bin/env python

import socket
from time import ctime

HOST=''
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

tcpSerSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
tcpSerSock.listen(5)

while True:
    print 'waiting for connection...'
	tcpCliSock,addr=tcpSerSock.accept()
	print '...connected from:',addr
	while True:
		data=tcpCliSock.recv(BUFSIZ)
		if not data:
			break
		print data
		tcpCliSock.send('[%s] %s' %(ctime(),data))
		
		
tcpCliSock.close()
tcpSerSock.close()